import { ref, reactive, shallowRef, watch } from 'vue';
import echarts from '@/echarts';
import { EChartsOption, RadarSeriesOption } from 'echarts';
import { EChartsType } from 'echarts/core';
import type { RadarChartType } from '../data';

import { getHtmlFontPX, handleChartResize } from '@/utils/base';
import { colorList } from '../config';
import ThemeColor from '@/themeColor';
import useGithubStore from '@/store/github';
import { message } from 'ant-design-vue';
import { RadarOption } from 'echarts/types/dist/shared';
import { GitHubItem } from './use-github';

export default function (): RadarChartType {
	const githubStore = useGithubStore();

	const chartRef = shallowRef<EChartsType>();
	const container = ref<HTMLDivElement | undefined>();
	const chart = reactive<RadarChartType['chart']>({
		selectValue: [],
		initChart,
		resizeChart,
		addRadarData
	});
	const option = {
		grid: {
			left: '2%',
			right: '2%',
			bottom: '3%',
			top: '5%',
			containLabel: true
		},
		tooltip: {
			trigger: 'axis'
		},
		xAxis: [
			{
				type: 'category',
				boundaryGap: true,
				data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
				axisLine: {
					lineStyle: {
						color: '#FFC945',
						width: 1 //x轴线的宽度
					}
				}
			}
		],
		yAxis: [
			{
				type: 'value',
				axisLine: {
					lineStyle: {
						color: '#FFC945',
						width: 1 //x轴线的宽度
					}
				},
				splitLine: false
			}
		],
		series: [
			{
				name: '数量',
				type: 'line',

				label: {
					show: true,
					position: 'top',
					textStyle: {
						color: '#FFD188'
					}
				},
				areaStyle: {
					opacity: 0.4,
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{ offset: 1, color: '#FFC945' },
						{ offset: 0, color: '#523D35 ' }
					])
				},
				emphasis: {
					focus: 'series'
				},
				itemStyle: {
					normal: {
						color: '#581F23', //改变折线点的颜色
						lineStyle: {
							color: '#FFC945 ' //改变折线颜色
						}
					}
				},
				data: [820, 932, 901, 934, 1290, 1330, 1320]
			}
		]
	};
	const indicator = ref<RadarOption['indicator']>([
		{ name: 'Influence', max: 120 },
		{ name: 'Response', max: 120 },
		{ name: 'Activity', max: 120 },
		{ name: 'Trend', max: 120 },
		{ name: 'GitHub', max: 120 }
	]);
	/**
	 * @description 计算设置最大值
	 */
	function calcMax() {
		const maxObj: Record<string, any> = chart.selectValue.reduce(
			(max, item) => {
				max.influence = Math.max(max.influence, +item.influence);
				max.response = Math.max(max.response, +item.response);
				max.activity = Math.max(max.activity, +item.activity);
				max.trend = Math.max(max.trend, +item.trend);
				max.github = Math.max(max.github, +item.github);
				return max;
			},
			{ influence: 0, response: 0, activity: 0, trend: 0, github: 0 }
		);
		Object.keys(maxObj).forEach((key, index) => {
			indicator.value![index].max = +maxObj[key] + 20;
		});
	}

	/**
	 * 初始化图表
	 * @param container 图表容器id
	 */
	function initChart(nodes: GitHubItem[]): any {
		if (!container.value) return;
		option.xAxis[0].data = Object.keys(nodes);
		option.series[0].data = Object.values(nodes);
		chartRef.value = echarts.init(container.value);
		chartRef.value && chartRef.value.setOption(option);
	}

	/**
	 * @description 重新set一下resize后的字体 不然会有偏移
	 */
	function resetFontSize() {
		delete option.series;
		// 需要重新计算字体不然依旧会有点偏差
		chartRef.value && chartRef.value.setOption(option);
	}

	/**
	 * @description 处理图表resize
	 */
	function resizeChart() {
		if (chartRef.value) {
			handleChartResize(chartRef.value);
			resetFontSize();
		}
	}

	/**
	 * @description 雷达图添加
	 */
	function addRadarData(name: string) {
		if (chart.selectValue.find(item => item.name === name)) {
			return message.warning('不能重复添加');
		}

		if (chart.selectValue.length >= 5) {
			return message.warning('最多添加5项');
		}

		const item = githubStore.list.find(item => item.name === name)!;
		const obj = {
			value: [item.influence, item.response, item.activity, item.trend, item.github],
			name: item.name,
			areaStyle: { opacity: 0.2 }
		};
		const curOptions = chartRef.value?.getOption();

		if (curOptions && Array.isArray(curOptions.series)) {
			chart.selectValue.push(item);
			curOptions.series[0].data.push(obj);
			calcMax();
			(curOptions.radar as any)[0].indicator = indicator.value;
			chartRef.value?.setOption(curOptions);
		}
	}

	// watch(
	// 	() => chartRef.value,
	// 	() => {
	// 		chartRef.value &&
	// 			chartRef.value.on('showTip', () => {
	// 				document.querySelector('#radar-remove')?.addEventListener('click', e => {
	// 					const name = (e.target as HTMLDivElement).dataset.id;
	// 					const curOptions = chartRef.value?.getOption();
	// 					if (curOptions && Array.isArray(curOptions.series)) {
	// 						const index = chart.selectValue.findIndex(item => item.name === (name as string));
	// 						chart.selectValue.splice(index, 1);
	// 						curOptions.series[0].data = curOptions.series[0].data.filter((item: any) => item.name !== name);
	// 						calcMax();
	// 						(curOptions.radar as any)[0].indicator = indicator.value;
	// 						chartRef.value?.setOption(curOptions, true);
	// 					}
	// 				});
	// 			});
	// 	}
	// );

	return {
		chart,
		container,
		chartRef
	};
}
